// 执行状态管理
import { defineStore } from 'pinia'

export const useExecutionStore = defineStore('execution', {
  state: () => ({
    isRunning: false,
    isPaused: false,
    currentStepIndex: -1,
    executionSpeed: 1, // 执行速度倍率
    breakpoints: [], // 断点列表
    executionResults: [], // 执行结果
    startTime: null,
    endTime: null,
    totalSteps: 0,
    completedSteps: 0,
    failedSteps: 0,
    logs: []
  }),

  getters: {
    // 为了兼容RecorderView中的isExecuting
    isExecuting: (state) => state.isRunning,
    
    progress: (state) => {
      if (state.totalSteps === 0) return 0
      return (state.completedSteps / state.totalSteps) * 100
    },
    
    currentExecutionTime: (state) => {
      if (!state.startTime) return 0
      const endTime = state.endTime || new Date()
      return endTime - state.startTime
    },
    
    executionStatus: (state) => {
      if (state.isRunning) return 'running'
      if (state.isPaused) return 'paused'
      if (state.completedSteps === state.totalSteps && state.totalSteps > 0) return 'completed'
      if (state.failedSteps > 0) return 'failed'
      return 'ready'
    },
    
    hasBreakpoints: (state) => state.breakpoints.length > 0
  },

  actions: {
    // 开始执行
    startExecution(steps = []) {
      this.isRunning = true
      this.isPaused = false
      this.currentStepIndex = 0
      this.startTime = new Date()
      this.endTime = null
      this.totalSteps = steps.length
      this.completedSteps = 0
      this.failedSteps = 0
      this.executionResults = []
      
      this.addLog('info', `开始执行脚本，共 ${this.totalSteps} 个步骤`)
    },

    // 执行所有步骤
    async executeAll(steps = []) {
      try {
        this.startExecution(steps)
        
        // 模拟执行过程
        for (let i = 0; i < steps.length; i++) {
          if (!this.isRunning || this.isPaused) break
          
          this.currentStepIndex = i
          await this.simulateStepExecution(steps[i], i)
          
          // 检查断点
          if (this.isAtBreakpoint(i)) {
            this.pauseExecution()
            break
          }
          
          // 添加延迟，模拟真实执行
          await new Promise(resolve => setTimeout(resolve, 1000 / this.executionSpeed))
        }
        
        if (this.currentStepIndex >= steps.length - 1) {
          this.completeExecution()
        }
        
        return { success: true }
      } catch (error) {
        this.addLog('error', `执行失败: ${error.message}`)
        this.stopExecution()
        throw error
      }
    },

    // 执行单个步骤
    async executeNextStep(steps = []) {
      try {
        if (!this.isRunning) {
          this.startExecution(steps)
        }
        
        if (this.currentStepIndex < 0) {
          this.currentStepIndex = 0
        } else {
          this.currentStepIndex++
        }
        
        if (this.currentStepIndex >= steps.length) {
          this.completeExecution()
          return { success: false, message: '已到达最后一步' }
        }
        
        const step = steps[this.currentStepIndex]
        await this.simulateStepExecution(step, this.currentStepIndex)
        
        return { success: true, stepIndex: this.currentStepIndex }
      } catch (error) {
        this.addLog('error', `步骤执行失败: ${error.message}`)
        throw error
      }
    },

    // 模拟步骤执行
    async simulateStepExecution(step, stepIndex) {
      try {
        this.addLog('info', `开始执行步骤 ${stepIndex + 1}: ${step.description}`)
        
        // 模拟执行时间
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 大部分步骤成功，少数失败（为了演示）
        const shouldFail = Math.random() < 0.1 // 10% 失败率
        
        if (shouldFail && step.type !== 'navigation') {
          throw new Error('模拟执行失败')
        }
        
        this.markStepCompleted(stepIndex, { result: '执行成功' })
      } catch (error) {
        this.markStepFailed(stepIndex, error)
        throw error
      }
    },

    // 暂停执行（兼容方法）
    pause() {
      return this.pauseExecution()
    },

    // 恢复执行（兼容方法）
    resume() {
      return this.resumeExecution()
    },

    // 暂停执行
    pauseExecution() {
      this.isPaused = true
      this.addLog('info', '执行已暂停')
    },

    // 恢复执行
    resumeExecution() {
      this.isPaused = false
      this.addLog('info', '执行已恢复')
    },

    // 停止执行
    stopExecution() {
      this.isRunning = false
      this.isPaused = false
      this.endTime = new Date()
      
      const duration = this.currentExecutionTime
      this.addLog('info', `执行已停止，用时 ${Math.round(duration / 1000)}s`)
    },

    // 完成执行
    completeExecution() {
      this.isRunning = false
      this.isPaused = false
      this.endTime = new Date()
      
      const duration = this.currentExecutionTime
      this.addLog('success', `执行完成，用时 ${Math.round(duration / 1000)}s，成功 ${this.completedSteps}/${this.totalSteps} 步`)
    },

    // 执行下一步
    executeNextStep() {
      if (!this.isRunning || this.isPaused) return false
      
      this.currentStepIndex++
      
      // 检查是否完成
      if (this.currentStepIndex >= this.totalSteps) {
        this.completeExecution()
        return false
      }
      
      return true
    },

    // 标记步骤完成
    markStepCompleted(stepIndex, result = {}) {
      this.completedSteps++
      this.executionResults[stepIndex] = {
        status: 'success',
        ...result,
        timestamp: new Date()
      }
      
      this.addLog('success', `步骤 ${stepIndex + 1} 执行成功`)
    },

    // 标记步骤失败
    markStepFailed(stepIndex, error = {}) {
      this.failedSteps++
      this.executionResults[stepIndex] = {
        status: 'failed',
        error: error.message || '执行失败',
        ...error,
        timestamp: new Date()
      }
      
      this.addLog('error', `步骤 ${stepIndex + 1} 执行失败: ${error.message || '未知错误'}`)
    },

    // 跳过步骤
    skipStep(stepIndex, reason = '') {
      this.executionResults[stepIndex] = {
        status: 'skipped',
        reason,
        timestamp: new Date()
      }
      
      this.addLog('warn', `步骤 ${stepIndex + 1} 已跳过${reason ? ': ' + reason : ''}`)
    },

    // 添加断点
    addBreakpoint(stepIndex) {
      if (!this.breakpoints.includes(stepIndex)) {
        this.breakpoints.push(stepIndex)
        this.addLog('info', `在步骤 ${stepIndex + 1} 添加断点`)
      }
    },

    // 移除断点
    removeBreakpoint(stepIndex) {
      const index = this.breakpoints.indexOf(stepIndex)
      if (index > -1) {
        this.breakpoints.splice(index, 1)
        this.addLog('info', `移除步骤 ${stepIndex + 1} 的断点`)
      }
    },

    // 切换断点
    toggleBreakpoint(stepIndex) {
      if (this.breakpoints.includes(stepIndex)) {
        this.removeBreakpoint(stepIndex)
      } else {
        this.addBreakpoint(stepIndex)
      }
    },

    // 清空断点
    clearBreakpoints() {
      this.breakpoints = []
      this.addLog('info', '已清空所有断点')
    },

    // 检查是否在断点处
    isAtBreakpoint(stepIndex) {
      return this.breakpoints.includes(stepIndex)
    },

    // 设置执行速度
    setExecutionSpeed(speed) {
      this.executionSpeed = Math.max(0.1, Math.min(10, speed))
      this.addLog('info', `执行速度已设置为 ${this.executionSpeed}x`)
    },

    // 重置状态
    reset() {
      this.isRunning = false
      this.isPaused = false
      this.currentStepIndex = -1
      this.startTime = null
      this.endTime = null
      this.totalSteps = 0
      this.completedSteps = 0
      this.failedSteps = 0
      this.executionResults = []
      this.addLog('info', '执行状态已重置')
    },

    // 添加日志
    addLog(level, message) {
      this.logs.push({
        timestamp: new Date(),
        level,
        message
      })
      
      // 限制日志数量，保持最新的1000条
      if (this.logs.length > 1000) {
        this.logs = this.logs.slice(-1000)
      }
    },

    // 清空日志
    clearLogs() {
      this.logs = []
    },

    // 获取步骤结果
    getStepResult(stepIndex) {
      return this.executionResults[stepIndex] || null
    },

    // 获取步骤状态
    getStepStatus(stepNumber) {
      // stepNumber is 1-based, but our arrays are 0-based
      const stepIndex = stepNumber - 1
      
      // 如果当前正在执行这个步骤
      if (this.isRunning && this.currentStepIndex === stepIndex) {
        return 'running'
      }
      
      // 检查执行结果
      const result = this.executionResults[stepIndex]
      if (result) {
        return result.status // 'success', 'failed', 'skipped'
      }
      
      // 如果步骤还没有执行
      if (stepIndex > this.currentStepIndex) {
        return 'pending'
      }
      
      // 默认状态
      return 'ready'
    },

    // 获取执行摘要
    getExecutionSummary() {
      return {
        totalSteps: this.totalSteps,
        completedSteps: this.completedSteps,
        failedSteps: this.failedSteps,
        skippedSteps: this.executionResults.filter(r => r?.status === 'skipped').length,
        duration: this.currentExecutionTime,
        status: this.executionStatus,
        successRate: this.totalSteps > 0 ? (this.completedSteps / this.totalSteps) * 100 : 0
      }
    }
  }
})